"use strict";
const log = require("@dream/log");
const semver = require("semver");
const colors = require("colors/safe");
const userHome = require("user-home");
const pathExists = require("path-exists").sync;
const minimist = require("minimist");
const dotenv = require("dotenv");
const path = require("path");
const { getNpmLastVersion } = require("@dream/get-npm-info");

const pkg = require("../package.json");
const { LOWEST_VERSION, DEFAULT_CLI_HOME } = require("./const");
let args;

async function core() {
  try {
    checkPkgVersion();
    checkNodeVersion();
    checkRoot();
    checkUserHome();
    checkInputArgs();
    checkEnv();
    await checkGlobalUpdate();
  } catch (err) {
    log.error("cli", err.message);
  }
}

/**
 * 检查全局更新
 */
async function checkGlobalUpdate() {
  const curVersion = pkg.version;
  const name = pkg.name;
  const registry = pkg.publishConfig.registry;
  const lastVersion = await getNpmLastVersion(curVersion, name, registry);
  if (lastVersion && semver.gt(lastVersion, curVersion)) {
    log.warn(
      "更新提醒",
      colors.yellow(
        `${name}可更新，当前版本为${curVersion}, 最新版本为${lastVersion}`
      )
    );
  }
}

/**
 * 检查环境变量
 */
function checkEnv() {
  dotenv.config({
    path: path.resolve(userHome, ".env"),
  });
  getCliHome();
}

function getCliHome() {
  if (!process.env.CLI_HOME) {
    process.env.CLI_HOME = DEFAULT_CLI_HOME;
  }
  process.env.CLI_HOME_PATH = path.resolve(userHome, process.env.CLI_HOME);
}

/**
 * 检查入参
 */
function checkInputArgs() {
  args = minimist(process.argv.slice(2));
  log.level = args.debug ? "verbose" : "info";
}

/**
 * 检查用户主目录
 */
function checkUserHome() {
  if (!userHome || !pathExists(userHome)) {
    throw new Error(colors.red("当前登录用户主目录不存在!"));
  }
}

/**
 * 检查root启动
 */
function checkRoot() {
  const rootCheck = require("root-check");
  rootCheck();
}

/**
 * 判断node版本是否满足最低配置版本
 */
function checkNodeVersion() {
  const curVersion = process.version.slice(1);
  if (!semver.gte(curVersion, LOWEST_VERSION)) {
    throw new Error(
      colors.red(
        `node最低要求版本为${LOWEST_VERSION}, 你当前版本为${curVersion}`
      )
    );
  }
}

/**
 * 判断安装依赖版本
 */
function checkPkgVersion() {
  log.success("cli", pkg.version);
}

module.exports = core;
